import './index.less'
import {useEffect, useRef} from "react"  // 导入useRef
import 'mapbox-gl/dist/mapbox-gl.css'
import mapboxgl from 'mapbox-gl'
import useAppState from "../../store";
import {isEmpty} from "lodash";
import COLOR_SCALES_ARRAY from '../../constant.ts'
import * as d3 from 'd3';

const MapBox = () => {
    const {themeDateData, currentMode, mapData} = useAppState();
    const mapRef = useRef(null);          // 保存地图实例
    const themeMinMax = useRef({});       // 主题数据范围
    const sourcesRef = useRef(new Set()); // 记录已添加的源ID
    const layersRef = useRef(new Set());  // 记录已添加的图层ID
    const markersRef = useRef([]);        // 记录所有标记
    const svgRef = useRef();
    useEffect(() => {
        const tempMinMax = {};
        Object.keys(mapData).forEach(key => {
            const tempFrequency = [];
            Object.values(mapData[key]).forEach(value => {
                tempFrequency.push(value.Frequency)
            });
            tempMinMax[key] = {
                min: Math.min(...tempFrequency),
                max: Math.max(...tempFrequency)
            };
        });
        themeMinMax.current = tempMinMax;
        mapboxgl.accessToken = 'pk.eyJ1IjoiemR5MDIwODEyIiwiYSI6ImNtZ3pidTh1cjAzcmU2aHF1czQyYjVmeWsifQ.pFCDrk5WCYrTXNMbxulZMg'
        const map = new mapboxgl.Map({
            container: 'MapBox',
            style: 'mapbox://styles/mapbox/light-v11',
            center: [-8.62564, 41.150552],
            zoom: 14,
            pitch: 35,
            attributionControl: false,
        })
        // 向地图添加缩放和旋转控件, 默认为右上角
        map.addControl(new mapboxgl.NavigationControl());
        // 向地图添加比例尺, 默认左下角
        map.addControl(new mapboxgl.ScaleControl({maxWidth: 75, unit: 'metric'}));
        // 向地图添加全屏按钮,默认右上角
        map.addControl(new mapboxgl.FullscreenControl());
        mapRef.current = map;
        return () => {
            if (mapRef.current) {
                mapRef.current.remove();
                mapRef.current = null;
            }
        };
    }, [mapData]);
    // 转换数据为GeoJSON格式
    const convertToGeoJSON = (trajectories, id) => {
        return {
            type: 'FeatureCollection',
            features: trajectories.map((coords, index) => ({
                type: 'Feature',
                properties: {
                    id: id,
                    // color: colors[index]
                },
                geometry: {
                    type: 'LineString',
                    coordinates: coords
                }
            }))
        };
    };
    // 清理现有数据
    const clearExistingData = (map) => {
        // 清除标记
        markersRef.current.forEach(marker => marker.remove());
        markersRef.current = [];
        // 清除图层
        layersRef.current.forEach(layerId => {
            if (map.getLayer(layerId)) {
                map.removeLayer(layerId);
            }
        });
        layersRef.current.clear();

        // 清除数据源
        sourcesRef.current.forEach(sourceId => {
            if (map.getSource(sourceId)) {
                map.removeSource(sourceId);
            }
        });
        sourcesRef.current.clear();
    };
    // 处理数据更新（核心逻辑）
    const handleDataUpdate = (map) => {
        // 清除旧的标记、图层、数据源
        clearExistingData(map);
        if (currentMode === "Representative_Docs_gps") {
            themeDateData.forEach((item, index) => {
                item.dates.forEach((date) => {
                    const tempData = mapData[item.theme][date];
                    const sourceId = `trajectories-${tempData["id"]}`;
                    const layerId = `trajectory-lines-${tempData["id"]}`;
                    const range = themeMinMax.current[item.theme]["max"] - themeMinMax.current[item.theme]["min"]
                    const themeColorIndex = range === 0 ? 0 : Math.floor(4 * (tempData["Frequency"] - themeMinMax.current[item.theme]["min"]) / range);
                    // 添加轨迹数据源
                    map.addSource(sourceId, {
                        type: 'geojson',
                        data: convertToGeoJSON(tempData["Representative_Docs_gps"], tempData["id"])
                    });
                    sourcesRef.current.add(sourceId);
                    map.addLayer({
                        id: layerId,
                        type: 'line',
                        source: sourceId,
                        paint: {
                            'line-color': COLOR_SCALES_ARRAY[item.theme][themeColorIndex],
                            'line-width': 3,
                            'line-opacity': 1
                        }
                    });
                    layersRef.current.add(layerId);
                    // 添加坐标点标记
                    tempData.Representative_Docs_gps.forEach((lineCoords) => {
                        lineCoords.forEach((coord) => {
                            // 1. 创建悬浮提示框的DOM元素
                            const popup = new mapboxgl.Popup({
                                offset: 25, // 提示框相对于标记的偏移量
                                closeButton: false, // 不显示关闭按钮
                                closeOnClick: false // 点击地图不关闭提示框
                            }).setHTML(`
                      <div class="custom-popup">
                        <div>Topic: ${item.theme}</div>
                        <div>Date: ${date}</div>
                        <div>Frequency: ${tempData["Frequency"]}</div>
                      </div>
    `);                     const marker = document.createElement('div');
                            marker.className = 'custom-circle-marker';
                            marker.style.backgroundColor = COLOR_SCALES_ARRAY[item.theme][themeColorIndex];
                            marker.style.width = '14px';
                            marker.style.height = '14px';
                            marker.style.borderRadius = '50%';
                            marker.style.border = '2px solid white';

                            const tempMarker = new mapboxgl.Marker({element: marker})
                                .setLngLat(coord)
                                .setPopup(popup) // 可选：如果需要点击也能触发提示框
                                .addTo(map);
                            markersRef.current.push(tempMarker);
                        });
                    });
                })
            })
        } else {
            themeDateData.forEach((item, index) => {
                item.dates.forEach((date) => {
                    const tempData = mapData[item.theme][date];
                    const range = themeMinMax.current[item.theme]["max"] - themeMinMax.current[item.theme]["min"]
                    const themeColorIndex = range === 0 ? 0 : Math.floor(4 * (tempData["Frequency"] - themeMinMax.current[item.theme]["min"]) / range);
                    // 添加坐标点标记
                    tempData.Words_gps.forEach((coord) => {
                        // 1. 创建悬浮提示框的DOM元素
                        const popup = new mapboxgl.Popup({
                            offset: 25, // 提示框相对于标记的偏移量
                            closeButton: false, // 不显示关闭按钮
                            closeOnClick: false // 点击地图不关闭提示框
                        }).setHTML(`
                      <div class="custom-popup">
                        <div>Topic: ${item.theme}</div>
                        <div>Date: ${date}</div>
                        <div>Frequency: ${tempData["Frequency"]}</div>
                      </div>
    `);
                        const marker = document.createElement('div');
                        marker.className = 'custom-circle-marker';
                        marker.style.backgroundColor = COLOR_SCALES_ARRAY[item.theme][themeColorIndex];
                        marker.style.width = '14px';
                        marker.style.height = '14px';
                        marker.style.borderRadius = '50%';
                        marker.style.border = '2px solid white';

                        const tempMarker = new mapboxgl.Marker({element: marker})
                            .setLngLat(coord)
                            .setPopup(popup) // 可选：如果需要点击也能触发提示框
                            .addTo(map);
                        markersRef.current.push(tempMarker);
                    });
                })
            })
        }
    }
    const drawColorLegend = (themeDateData) => {
        const data = themeDateData.map((item, index) => ({theme: item.theme, colors: COLOR_SCALES_ARRAY[item.theme]}))
        const margin = 5; // 长方形间距
        const barWidth = 130; // 单个长方形总宽度
        const barHeight = 15; // 单个长方形高度
        const textHeight = 20;
        const rightTextWidth = 65;
        const leftTextWidth = 80;
        const svg = d3.select(svgRef.current).attr("height", (barHeight + margin) * data.length + textHeight).attr("width", leftTextWidth + rightTextWidth + barWidth)

        // 创建主容器分组
        const bars = svg.selectAll('g.color-bar')
            .data(data)
            .join('g')
            .attr('class', 'color-bar')
            .attr('transform', (d, i) => `translate(${leftTextWidth}, ${i * (barHeight + margin)})`);
        svg.selectAll('text.color-text')
            .data(data)
            .join('text')
            .attr('class', 'color-text')
            .style('font-size', '14px')
            .attr('dy', '0.38em')
            // .style('font-weight', "bold")
            .attr('transform', (d, i) => `translate(${leftTextWidth + barWidth + margin}, ${i * (barHeight + margin) + barHeight / 2})`)
            .text((d, i) => `Topic ${d.theme}`);
        const bottomLeftText = svg.select('#bottom-left-text');
        if (bottomLeftText.empty()) svg.append('text')
            .attr("id", "bottom-left-text")
            .style('text-anchor', 'middle')
            .text("Min Frequency")
            .style('font-size', '14px')
            .attr('transform', (d, i) => `translate(${leftTextWidth}, ${(barHeight + margin) * data.length + margin * 3})`)
        else {
            bottomLeftText.attr('transform', (d, i) => `translate(${leftTextWidth}, ${(barHeight + margin) * data.length + margin * 3})`)
        }
        const bottomRightText = svg.select('#bottom-right-text');
        if (bottomRightText.empty()) svg.append('text')
            .attr("id", "bottom-right-text")
            .style('text-anchor', 'middle')
            .text("Max Frequency")
            .style('font-size', '14px')
            .attr('transform', (d, i) => `translate(${leftTextWidth + barWidth}, ${(barHeight + margin) * data.length + margin * 3})`)
        else {
            bottomRightText.attr('transform', (d, i) => `translate(${leftTextWidth + barWidth}, ${(barHeight + margin) * data.length + margin * 3})`)
        }
        // 创建每个分段的矩形
        bars.each(function (data) {
            const segmentWidth = barWidth / data.colors.length;
            d3.select(this)
                .selectAll('rect.segment')
                .data(data.colors)
                .join('rect')
                .attr('class', 'segment')
                .attr('x', (d, i) => i * segmentWidth)
                .attr('width', segmentWidth)
                .attr('height', barHeight)
                .attr('fill', d => d);
        });
    }
    useEffect(() => {
        const map = mapRef.current;
        if (!map || !svgRef.current || isEmpty(themeDateData)) return;
        drawColorLegend(themeDateData);
        // 确保地图已加载
        if (!map.isStyleLoaded()) {
            map.once('load', () => handleDataUpdate(map));
        } else {
            handleDataUpdate(map);
        }
    }, [themeDateData, currentMode])  // 空依赖确保只运行一次

    return <div id="MapBox">
        <svg ref={svgRef} id={"colorLegend"}></svg>
    </div>
}

export default MapBox
